import axios from 'axios'
import util from './myutils.js'
import that from '../main.js'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

//请求前统一拦截
service.interceptors.request.use(
  config => {
    //除了登录接口以外请求头需要携带token
    if (config.url == '/sys/login/do_login') {
      return config
    } else {
      config.headers['Authorization'] = localStorage.getItem('token')
    }
    return config
  },
  error => {
    util.showMsg(error)
    return Promise.reject(error)
  }
)

//响应后统一拦截
service.interceptors.response.use(
  response => {
    //后台做过捕获异常
    if(response.status == 200 && response.data.code == 500){
      util.showMsg(response.data.message, 'error')
    }
    if(response.headers) {
      response.data.contentHeaders = response.headers
    }
    let msg = ''
    switch(response.data.code){
      case 8888:  //账号权限发生变化
        that.$store.commit('setIsOutLogin', true)
        that.$store.commit('setCodeDistinguish', 'edit')
        msg = '权限变更，请重新登录'
        break;
      case 403: //登录过期
        // util.showMsg(response.data.message, 'error')
        msg = '登录过期，请重新登录'
        localStorage.removeItem('token')
        break;
      case 7777:  //账号被停用
        that.$store.commit('setIsOutLogin', true)
        that.$store.commit('setCodeDistinguish', 'stop')
        msg = '该账号已被停用'
        break;
    }
    if(response.data.code == 403) {
      that.$router.push('/login')
      that.$message({type:'error',message:msg});
    }
    return response.data
  },
  error => {
    //响应错误 统一处理消息提示框
    util.showMsg(error, 'error')
    return Promise.reject(error)
  }
)

export default service